package com.woniu.yoga_zuul.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import com.woniu.yoga_zuul.until.JWTHelper;

import io.jsonwebtoken.Claims;
import org.example.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AuthFilter extends ZuulFilter {
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.RIBBON_ROUTING_FILTER_ORDER-1;
    }

    @Override
    public boolean shouldFilter() {
        System.out.println("进入网管");
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String requestURI = request.getRequestURI();
        String login=requestURI.split("/")[2];
        if("login".equals(login)){
            return true;
        }else if("register".equals(login)){
            return true;
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String authToken = request.getHeader("auth_token");

        try{
            Claims claims = JWTHelper.parseJWT(authToken);
            currentContext.addZuulRequestHeader("userId", ""+ claims.get("userId"));
            currentContext.addZuulRequestHeader("username", (String) claims.get("username"));
            currentContext.setSendZuulResponse(true);
        }catch (Exception e){
            e.printStackTrace();
            currentContext.setSendZuulResponse(false);
            Result error = Result.Error(501, "请先登入");
            try {
                currentContext.setResponseBody(objectMapper.writeValueAsString(error));
            } catch (JsonProcessingException jsonProcessingException) {
                jsonProcessingException.printStackTrace();
            }
        }


        return null;
    }
}
